package com.wz.myvideoview.view;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wz.myvideoview.R;
import com.wz.myvideoview.util.Util;

import java.util.Formatter;
import java.util.Locale;

/**
 * Created by ren on 2017/10/23.
 */

public class MyController extends FrameLayout implements View.OnClickListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnInfoListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener{
    private Context mContext;

    private String url;
    private FrameLayout mRoot_rl;
    private MyVideoView videoView;
    private FrameLayout fl_videoParent;
    private ImageView mImage;
    private ImageView mCenterStart;
    private LinearLayout mTop;
    private ImageView mBack;
    private TextView mTitle;
    private LinearLayout mBottom;
    private ImageView mRestartPause;
    private TextView mPosition;
    private TextView mDuration;
    private SeekBar mSeek;
    private ImageView mFullScreen;
    private ImageView iv_loading;

    //播放控件的动画
    private ObjectAnimator bufferAnimation;

    private boolean isTopBottomShow = false;
    //更新进度条进度定时器
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    //当前视屏的播放进度
    private int currentProgress;

    public MyController(Context context) {
        super(context);
        this.mContext = context;
        init(context);
    }

    public MyController(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(context);
    }

    public MyController(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(context);
    }

    private void init(Context context) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_controller, null);
        fl_videoParent = (FrameLayout) view.findViewById(R.id.fl_videoParent);
        videoView = (MyVideoView) view.findViewById(R.id.videoView);
        mRoot_rl = (FrameLayout) view.findViewById(R.id.root_rl);
        mCenterStart = (ImageView) view.findViewById(R.id.center_start);
        mImage = (ImageView) view.findViewById(R.id.image);

        mTop = (LinearLayout) view.findViewById(R.id.top);
        mBack = (ImageView) view.findViewById(R.id.back);
        mTitle = (TextView) view.findViewById(R.id.title);

        mBottom = (LinearLayout) view.findViewById(R.id.bottom);
        mRestartPause = (ImageView) view.findViewById(R.id.restart_or_pause);
        mPosition = (TextView) view.findViewById(R.id.position);
        mDuration = (TextView) view.findViewById(R.id.duration);
        mSeek = (SeekBar) view.findViewById(R.id.seek);
        mFullScreen = (ImageView) view.findViewById(R.id.full_screen);
        iv_loading = view.findViewById(R.id.iv_loading);
        addView(view);

//        view.setOnTouchListener(this);
    }

    /**
     * 播放器初始化
     *
     * @param url
     * @param thumbUrl
     */
    public void initVideo(String url, String thumbUrl, String title) {
        this.url = url;
        videoView.setVideoPath(url);
        mTitle.setText(title);

        LayoutParams lp = (LayoutParams) videoView.getLayoutParams();
        lp.width = (int) Util.getScreenWidth(mContext);
        lp.height = lp.width * 9 / 16;
        videoView.setLayoutParams(lp);

        LayoutParams lp2 = (LayoutParams) mImage.getLayoutParams();
        lp2.width = (int) Util.getScreenWidth(mContext);
        lp2.height = lp2.width * 9 / 16;
        mImage.setLayoutParams(lp2);

        mTop.setVisibility(GONE);
        mBottom.setVisibility(GONE);

        Glide.with(mContext).load(thumbUrl).into(mImage);
        initListener();

        mRunnable = new Runnable() {
            @Override
            public void run() {
                float position = videoView.getCurrentPosition();
                currentProgress = (int) ((position / videoView.getDuration()) * 100);
                if (!isPlayOver) {
                    mSeek.setProgress(currentProgress);
                }
                mPosition.setText(stringForTime((int) position));
                mHandler.postDelayed(mRunnable, 500);
            }
        };
    }

    /**
     * 监听初始化
     */
    private void initListener() {
        mCenterStart.setOnClickListener(this);
        fl_videoParent.setOnClickListener(this);
        mRestartPause.setOnClickListener(this);
        mFullScreen.setOnClickListener(this);
        mBack.setOnClickListener(this);

        videoView.setOnPreparedListener(this);
        videoView.setOnInfoListener(this);
        videoView.setOnCompletionListener(this);
        mSeek.setOnSeekBarChangeListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.center_start:
                startPlay();
                if (url.startsWith("http") || url.startsWith("https")) {
                    iv_loading.setVisibility(VISIBLE);
                } else {
                    iv_loading.setVisibility(GONE);
                }
                startBufferAnimation();
                break;
            case R.id.fl_videoParent:
                if (videoView.isPlaying()) {
                    showHideTopAndBottom();
                }
                break;
            case R.id.restart_or_pause:
                if (videoView != null) {
                    if (videoView.isPlaying()) {
                        videoView.pause();
                        mRestartPause.setImageResource(R.drawable.ic_player_start);
                    } else {
                        startPlay();
                        mRestartPause.setImageResource(R.drawable.ic_player_pause);
                    }
                }
                break;
            case R.id.full_screen:
                switchScreenOrientation();
                break;
            case R.id.back:
                switchScreenOrientation();
                break;
        }
    }

    private void startPlay() {

        mRestartPause.setImageResource(R.drawable.ic_player_pause);
        videoView.start();
        mImage.setVisibility(GONE);
        mCenterStart.setVisibility(GONE);
    }

    /**
     * videoView准备完毕监听
     *
     * @param mediaPlayer
     */
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        stopBufferAnimation();
        iv_loading.setVisibility(GONE);

        mDuration.setText(stringForTime(videoView.getDuration()));
        mHandler.post(mRunnable);
    }

    /**
     * 缓冲标志动画
     */
    private void startBufferAnimation() {
        if (bufferAnimation == null) {
            bufferAnimation = ObjectAnimator.ofFloat(iv_loading, "rotation", 0, 359);
            bufferAnimation.setDuration(1500);
            bufferAnimation.setInterpolator(new LinearInterpolator());
            bufferAnimation.setRepeatCount(ObjectAnimator.INFINITE);
        }
        if (!bufferAnimation.isRunning()) {
            bufferAnimation.start();
        }
    }

    private void stopBufferAnimation() {
        if (bufferAnimation != null) {
            bufferAnimation.cancel();
        }
    }

    /**
     * 头部，底部隐藏显示
     */
    private void showHideTopAndBottom() {
        if (isTopBottomShow) {
            mTop.setVisibility(GONE);
            mBottom.setVisibility(GONE);
            isTopBottomShow = false;
        } else {
            mTop.setVisibility(VISIBLE);
            mBottom.setVisibility(VISIBLE);
            isTopBottomShow = true;
        }
    }

    @Override
    public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra) {
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {//开始缓冲
            iv_loading.setVisibility(VISIBLE);
            startBufferAnimation();
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {//缓冲结束
            iv_loading.setVisibility(GONE);
            stopBufferAnimation();
        }
        return false;
    }

    private String stringForTime(int timeMs) {
        if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
            return "00:00";
        }
        int totalSeconds = timeMs / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        StringBuilder stringBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    /**
     * seekBar进度改变实现方法
     *
     * @param seekBar
     * @param i
     * @param b
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //滑动SeekBar结束后让视屏定位到对应位置
        if (videoView != null) {
            int position = (int) ((seekBar.getProgress() * 1.0f /
                    seekBar.getMax()) * videoView.getDuration());
            videoView.seekTo(position);
        }
    }

    /**
     * 视频播放结束监听
     *
     * @param mediaPlayer
     */
    private boolean isPlayOver = false;

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        mImage.setVisibility(VISIBLE);
        mCenterStart.setVisibility(VISIBLE);
        mSeek.setProgress(0);

        mTop.setVisibility(VISIBLE);
        mBottom.setVisibility(VISIBLE);
        isTopBottomShow = true;
        isPlayOver = true;
    }

    /**
     * 设置全屏
     */
    public boolean fullscreen = false;

    public void switchScreenOrientation() {
        Activity activity = (Activity) getContext();
        LayoutParams lp = (LayoutParams) videoView.getLayoutParams();

        if (fullscreen) {//全屏，也就是横屏
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            fullscreen = false;

            mBack.setVisibility(VISIBLE);
            lp.width = (int) Util.getScreenWidth(mContext);
            lp.height = (int) Util.getScreenHeight(mContext);
            videoView.setLayoutParams(lp);
            mFullScreen.setImageResource(R.drawable.ic_player_shrink);
        } else {//不是全屏，也就是竖屏
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            fullscreen = true;

            mBack.setVisibility(GONE);
            lp.width = (int) Util.getScreenWidth(mContext);
            lp.height = lp.width * 9 / 16;
            videoView.setLayoutParams(lp);
            mFullScreen.setImageResource(R.drawable.ic_player_enlarge);
        }
    }

    /**
     * 停止播放
     */
    public void onStop() {
        isPlayOver = false;
        mHandler.removeCallbacksAndMessages(null);
        videoView.stopPlayback();
        videoView = null;
    }

    /**
     * 返回键点击事件
     */
    public boolean onBackPressed() {
        if (!fullscreen) {
            switchScreenOrientation();
            return true;
        } else {
            return false;
        }
    }
    /**
     * dp转换为px
     */
    public int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
